import { defineComponent, onActivated, onBeforeUnmount, onDeactivated, onMounted, reactive, ref } from "vue";
import styles from "./index.module.less";
import { getBase64ByFile, imgPath } from "@/common/utils";
import { useStore as useUserStore } from "@/store/user";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import { $commonUploadImg } from "@/api/common/common";
import { $getPolicyFile, $userOrderCancel, $userOrderList } from "@/api/userCenter/userCenter";
import { $userAuthStatus } from "@/api/account/account";
import UserOrderPopup from "./popup/userOrderPopup/userOrderPopup";
import useDownload from "@/hooks/useDownload";
import Paypopup from "./popup/paypopup/paypopup";
import { message } from "ant-design-vue";
import useCacheWhenTo from "@/hooks/useKeepAlive";

export default defineComponent({
  name: 'userCenterIndex',
  setup() {
    // 设置缓存
    useCacheWhenTo(['userCenterOrderDetail']);
    const userStore = useUserStore();
    const router = useRouter();
    const download = useDownload();

    // 跳转路由path
    const toPath = (path: string) => {
      router.push(path);
    };

    const personalInfo = reactive({
      bracket: 17,
      head_img: imgPath('/userCenter/photo.png'),
      status: 1,//是否认证
    } as any);

    const state = reactive({
      fileList: [],
      uploading: false,
      upload: (e: any) => {
        getBase64ByFile(e)
          .then((base64_img: any) => {
            $commonUploadImg({ base64_img })
              .then((res: any) => {
                personalInfo.head_img = res.data?.url || "";
                state.uploading = false;
              })
              .catch(() => {
                state.uploading = false;
              });
          })
          .catch(() => {
            state.uploading = false;
          });
        return false;
      },
      today: '',
    })
    //个人账户信息
    const AccountArea = () => (
      <div class={styles['account-area']}>
        <div class={styles['account-info']}>
          <div class={styles['photo-box']}>
            <div class={styles.photo}>
              <img src={personalInfo.head_img} />
              {/* <a-upload
                v-model:file-list={state.fileList}
                name="file"
                showUploadList={false}
                beforeUpload={state.upload}
              >
                <div class={styles.upload}>
                  <img src={imgPath('/userCenter/upload.png')} />
                  <div class={styles.word}>
                    上传新图片
                  </div>
                </div>
              </a-upload> */}
            </div>
          </div>
          <div class={styles.names}>{userStore.user_info.username}</div>
          <div class={styles.bracket}>
            <span class={styles.tps}>安全</span>
            {
              new Array(personalInfo.bracket).fill('').map(() => (
                <span class={styles.block}></span>
              ))
            }
            <span class={styles.senior}>高级</span>
          </div>
          <div class={styles['certification-info']}>
            <div class={styles['certification-infoItem']}>
              <img src={imgPath('/userCenter/certification-infoImg1.png')} />
              <span>已绑定</span>
            </div>
            <div class={styles['certification-infoItem']} onClick={() => { goCertification() }}>
              {
                personalInfo.status === 20 ?
                  <>
                    <img src={imgPath('/userCenter/certification-infoImg2.png')} />
                    <span>已认证企业</span>
                  </> :
                  <>
                    <img src={imgPath('/userCenter/certification-infoImg4.png')} />
                    <span style={{ color: '#999' }}>未认证企业</span>
                  </>
              }
            </div>
            {
              personalInfo.status === 20 && <div class={styles['certification-infoItem']} onClick={() => { toPath('/userCenter/PrePaidDepositAccount') }}>
                <img src={imgPath('/userCenter/certification-infoImg3.png')} />
                <span>预缴存入口</span>
              </div>
            }
          </div>
        </div>
        <div class={styles['app-info']}>
          <div class={styles['app-info-top']}>
            <img src={imgPath('/userCenter/app-info-topImg.png')} />
            <span>预缴存账户</span>
          </div>
          <div class={styles['app-info-center']}>
            {
              personalInfo.status === 20 && <>
                <div class={styles['advance-money']}>账户余额</div>
                <div class={styles['advance-info']}>{userStore.user_info.balance || 0.00}</div>
              </>
            }
            <div class={styles['detail']} onClick={() => { toPath('/userCenter/PrePaidDepositAccount') }}>查看账户详情</div>
          </div>
        </div>
      </div>
    )
    const orderList = reactive({
      menu: [
        {
          text: '全部订单',
        },
        {
          text: '待支付',
        },
        {
          text: '待出单',
        },
        {
          text: '出单失败',
        },
        {
          text: '已出单',
        },
        {
          text: '已退保',
        },
        {
          text: '已支付',
        },
        {
          text: '已取消',
        },
      ],
      menuActived: 0,
      list: [],
      total: 0,
      page: 1,
      pageSize: 10,
      picc_order_status: null,
      order_status: null,
    } as any)

    const menuClick = (index: any) => {
      orderList.menuActived = index;
      switch (index) {
        case 0:
          orderList.order_status = null;
          orderList.picc_order_status = null;
          break;
        case 1:
          orderList.order_status = 0;
          orderList.picc_order_status = null;
          break;
        case 2:
          orderList.order_status = null;
          orderList.picc_order_status = 0;
          break;
        case 3:
          orderList.order_status = null;
          orderList.picc_order_status = -1;
          break;
        case 4:
          orderList.order_status = null;
          orderList.picc_order_status = 1;
          break;
        case 5:
          orderList.order_status = 999;
          orderList.picc_order_status = null;
          break;
        case 6:
          orderList.order_status = 11;
          orderList.picc_order_status = null;
          break;
        case 7:
          orderList.order_status = 1000;
          orderList.picc_order_status = null;
          break;
      }
      getUserOrderList()
    }

    const getUserOrderList = () => {
      $userOrderList({
        picc_order_status: orderList.picc_order_status,
        order_status: orderList.order_status,
        page: orderList.page,
        limit: orderList.pageSize,
      }).then((res: any) => {
        orderList.list = res?.data?.data || [];
        orderList.total = res?.data?.total;
        orderList.page = res?.data?.current_page;
        orderList.pageSize = res?.data?.per_page;
      })
    }

    //跳页
    const onChange = (page: number, pageSize: number) => {
      orderList.page = page;
      orderList.pageSize = pageSize;
      const dom: any = document.getElementById("app");
      dom.scrollTop = 250;
      getUserOrderList();
    }
    // dom scroll 节点
    const scroll = ref(null as any);
    // 滚动条上拉距离
    const scrollTop = ref(0);

    // 记录滚动条上拉距离
    const handleScroll = (e: any) => {
      let scrollTops = e.target.scrollTop;
      scrollTop.value = scrollTops;
    }

    onMounted(() => {
      getUserOrderList();
      $userAuthStatus().then((res: any) => {
        personalInfo.status = res.data?.status || '';
      })
      let today = new Date();
      let year = today.getFullYear();
      let month = ('0' + (today.getMonth() + 1)).slice(-2);
      let day = ('0' + today.getDate()).slice(-2);
      state.today = year + '-' + month + '-' + day;
    })

    // 激活页面时设置滚动条置为记录的上拉距离
    onActivated(() => {
      (document.getElementById("userCenterScroll") as any).scrollTop = scrollTop.value;
      document.getElementById("userCenterScroll")?.addEventListener("scroll", handleScroll);
    });

    onDeactivated(() => {
      document.getElementById("userCenterScroll")?.removeEventListener("scroll", handleScroll);
    })

    const userOrderRef = ref(null as any);
    const paypopupRef = ref(null as any);

    //下载电子保单
    const getPolicyFile = (order_no: string) => {
      $getPolicyFile({ order_no: order_no, }).then((res: any) => {
        download.downloadFile(res.data?.url);
      })
    }
    //取消订单
    const orderCancel = (order_no: string) => {
      $userOrderCancel({ order_no: order_no }).then((res: any) => {
        message.success('订单取消成功');
        getUserOrderList();
      })
    }
    //支付订单
    const payOrder = (item: any) => {
      // if (state.today > Number((new Date('2024-07-25').getTime()).toFixed(0))) {
      //   message.error('晚')
      // } else {
      //   message.error('早')
      // }
      paypopupRef.value.open(item);
    }
    //列表
    const OrderList = () => (
      <div class={styles['order-list']}>
        <div class={styles['order-list-menu']}>
          {
            orderList.menu.map((itemY: any, index: number) => (
              <div class={styles['menu-item']} onClick={() => { menuClick(index) }}>
                <span class={[styles.text,
                index === orderList.menuActived && styles['menu-item-actived'],
                index !== orderList.menuActived && styles['menu-item-noActived']]}
                >{itemY.text}</span>
              </div>
            ))
          }
        </div>
        <div class={styles['order-list-thead']}>
          <div class={styles['col-first']}>订单详情<span class={styles.tips}>(待支付订单中只能在起保日期之前进行支付，起保时间当天及以后无法支付)</span></div>
          <div class={styles['col-last']}>状态/保费(元)</div>
          <div class={styles['col-three']}>操作</div>
        </div>
        {
          orderList.list.length === 0 ?
            <div class={styles['order-list-content']}>
              <img src={imgPath('/home/no-message.jpg')} />
            </div> :
            <div>
              {
                orderList.list.map((item: any) => (
                  <div class={styles['order-item']}>
                    <div class={styles['order-item-headerBox']}>
                      <span class={styles.orderNum}>订单号：{item.order_no}</span>
                      <span>下单时间：{item.create_time}</span>
                      <div class={styles.fr}>
                        <a-dropdown placement="bottom" v-slots={{
                          overlay: () => (
                            <div class={styles.dropDown}>
                              <span>企业信息变更</span>
                              <span>分社变更</span>
                              <span>保额变更</span>
                              <span>经营资质变更</span>
                              <span>退保</span>
                            </div>
                          )
                        }}>
                          <span>批改保单</span>
                        </a-dropdown>
                      </div>
                    </div>
                    <div class={styles['order-item-content']}>
                      <div class={styles['order-item-info']}>
                        <img src={imgPath('/userCenter/orderImg.png')} />
                        <div class={styles['prod-info']}>
                          <div class={styles.title}>{item.name}{item.plan_name}</div>
                          <div class={styles['order-item-row']}>
                            <span>保险期间：{item.start_date}至{item.end_date}</span>
                          </div>
                          <div class={styles['order-item-row']}>
                            <span>投保人：{item.applicant_name}</span>
                          </div>
                          {
                            item.picc_order ? <>
                              <div class={styles['order-item-row']}>
                                <span>投保单号：{item.picc_order.proposal_no}</span>
                              </div>
                              <div class={styles['order-item-row']}>
                                <span>出单时间：{item.picc_order.create_time}</span>
                              </div>
                              <div class={styles['order-item-row']}>
                                <span>发票状态：{item.picc_order.invoice_status.label}</span>
                              </div>
                              <div class={styles['order-item-row']}>
                                <span>保单号：</span><span class={styles.value}>{item.picc_order.policy_no}</span>
                              </div>
                            </> : <div style={{ display: 'none' }}>
                              1231</div>
                          }
                        </div>
                      </div>
                      <div class={styles['order-item-money']}>
                        {
                          (orderList.menuActived === 1 || orderList.menuActived === 5 || orderList.menuActived === 7) ?
                            <div class={styles.status}>{item.order_status.label}</div> : <div class={styles.status}>{item.picc_order_status.label}</div>
                        }
                        <div class={styles.money}>标准保费：￥{item.sum_premium}</div>
                        <div class={styles.money}>实付金额：￥{item.sum_premium}</div>
                        <div>{item.pay_type_name}</div>
                      </div>
                      <div class={styles['order-item-operate']}>
                        {
                          item.picc_order_status.label === '已出单' && <div class={styles.download} onClick={() => { getPolicyFile(item.order_no) }}>下载电子保单</div>
                        }
                        {
                          (item.order_status.label === '待支付' &&
                            (Number((new Date(state.today).getTime()).toFixed(0)) < Number((new Date(item.start_date).getTime()).toFixed(0)))
                          ) && <div class={styles.download} onClick={() => { payOrder(item) }}>去支付</div>
                        }
                        {
                          item.order_status.label === '待支付' && <div class={styles.download} onClick={() => { orderCancel(item.order_no) }}>取消订单</div>
                        }
                        <span class={styles.detail} onClick={() => {
                          router.push(`/userCenter/index/orderDetail?order_no=${item.order_no}`);
                          // const dom: any = document.getElementById("app");
                          // dom.scrollTop = 0;
                        }}>订单详情</span>
                      </div>
                    </div>
                  </div>
                ))
              }
              <div class={styles.pagination}>
                <a-pagination total={orderList.total} v-model:current={orderList.page} pageSize={orderList.pageSize} onChange={(page: any, pageSize: any) => { onChange(page, pageSize) }} />
              </div>
            </div>
        }
      </div>
    )
    //前往认证
    const goCertification = () => {
      toPath('/account/Qyinform/EnterpriseInformation')
    }
    return () => (
      <div class={styles.index}>
        <div class={styles['header-box']}>
          <img src={imgPath('/userCenter/notice.png')} />
          <span>欢迎您进入中联E保，查看更多个人信息及保单信息</span>
        </div>
        {
          personalInfo.status === 20 || <div class={styles['tips-box']}>
            <div class={styles.row}>
              <img class={styles.icon} src={imgPath('/userCenter/icon.png')} />
              <span>尊敬的用户，您需要将个人账户升级成企业实名认证后，才能使用全部功能，升级企业实名认证后，该账号将归实名认证的企业所有</span>
            </div>
            <div class={styles.row}>
              <div class={styles.btn} onClick={() => { goCertification() }}>
                {
                  Number(personalInfo.status) === 0 ? <span>前往认证</span> : <span>认证中</span>
                }
              </div>
            </div>
          </div>
        }
        <AccountArea />
        <OrderList />
        <UserOrderPopup ref={userOrderRef} />
        <Paypopup ref={paypopupRef} />
      </div>
    )
  }
})